package cat.music.ut.comm

import android.content.Context
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import cat.music.ut.component.dp2px
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target

object GlideUtils {
    fun displayImage(context: Context, img: Any, imageView: ImageView) {
        Glide.with(context).load(img)
            .into(imageView);//四周都是圆角的圆角矩形图片。
    }

    fun displayRoundImage(context: Context, img: Int, imageView: ImageView, round: Int) {
        Glide.with(context).load(img)
            .apply(RequestOptions.bitmapTransform(RoundedCorners(dp2px(context, round))))
            .into(imageView);//四周都是圆角的圆角矩形图片。
    }

    fun displayDefeat(context: Context, img: Any?, imageView: ImageView, error: Int) {
        Glide.with(context).load(img).error(error)
            .into(imageView);//四周都是圆角的圆角矩形图片。
    }

    fun displayRoundImage(context: Context, img: Uri, imageView: ImageView, round: Int) {
        Glide.with(context).load(img)
            .apply(RequestOptions.bitmapTransform(RoundedCorners(dp2px(context, round))))
            .into(imageView);//四周都是圆角的圆角矩形图片。
    }

    fun displayRoundImage(context: Context, img: Any?, imageView: ImageView, round: Int) {
        val roundOptions = RequestOptions().transform(RoundedCorners(dp2px(context, round)))
//处理CenterCrop的情况,保证圆角不失效
        roundOptions.transform(CenterCrop(), RoundedCorners(dp2px(context, round)))

        Glide.with(context).load(img)
            .apply(roundOptions)
            .addListener(object : RequestListener<Drawable> {

                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable>?,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

            }).into(imageView)
    }
}